import React, { useState, useEffect, Fragment } from 'react';
import { Input, InputNumber, Select, Cascader, Switch, DatePicker } from 'antd';
import { Button } from 'eaid'
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import QuestionTip from '@/components/tooltip/QuestionTip';
import { App } from 'antd';
import dayjs from 'dayjs';
import useWindowWidth from '@/hooks/event/use-window-width';

interface FormItem {
  type: string;
  key: string;
  label: string;
  description?: string;
  value?: string | number | string[] | boolean;
  defaultValue?: string | number | string[] | boolean;
  valueType: string;
  required: boolean;
  isArray?: boolean;
  pattern?: string; // 用于 DatePicker 的格式
  minLength?: number; // 最小长度
  maxLength?: number; // 最大长度
  min?: number; // 最小值
  max?: number; // 最大值
  minItems?: number; // 数组最小项数
  maxItems?: number; // 数组最大项数
  list?: Array<{
    label: string;
    value: string;
    children?: Array<{
      label: string;
      value: string;
      children?: Array<{
        label: string;
        value: string;
      }>;
    }>;
  }>;
}

interface FormRendererProps {
  formItems: FormItem[];
  description?: string;
  isLastOne: boolean;
  itemText: boolean;
  onSend: (values: string) => void;
  columns?: number; // 可配置的列数，默认为4
  labelWidth?: string; // 参数名宽度，支持百分比(如'30%')或像素值(如'200px')，默认为'25%'
  // 示例：
  // labelWidth="30%" - 参数名占30%宽度，参数值占70%宽度
  // labelWidth="200px" - 参数名固定200px宽度，参数值占剩余宽度
}

const FormRenderer: React.FC<FormRendererProps> = ({
  formItems,
  description,
  isLastOne,
  itemText,
  onSend,
  columns = 4,
  labelWidth = '25%',
}) => {
  const [formValues, setFormValues] = useState<Record<string, any>>({});
  const { message } = App.useApp();
  const { isPc } = useWindowWidth();


  // 初始化 formValues，防止分页切换丢失已填写内容
  useEffect(() => {
    if (formItems) {
      const initialValues: Record<string, any> = {};
      formItems.forEach((formItem) => {
        if (formItem.isArray) {
          // 数组类型的表单项初始化
          let valueArr: any[] = [];
          if (formItem.value === '' || formItem.value === undefined) {
            if (Array.isArray(formItem.defaultValue)) {
              valueArr = formItem.defaultValue;
            } else if (formItem.defaultValue !== undefined && formItem.defaultValue !== '') {
              valueArr = [formItem.defaultValue];
            } else {
              valueArr = [];
            }
          } else {
            if (Array.isArray(formItem.value)) {
              valueArr = formItem.value;
            } else {
              valueArr = [formItem.value];
            }
          }
          initialValues[formItem.key] = valueArr;
        } else {
          // 非数组类型的表单项初始化
          initialValues[formItem.key] = (formItem.value === '' || formItem.value === undefined)
            ? (formItem.defaultValue ?? '')
            : formItem.value;
        }
      });
      setFormValues((prev) => ({ ...initialValues, ...prev }));
    }
  }, [formItems]);

  // 检查必填项是否已填写
  const checkRequiredFields = (items: FormItem[]) => {
    const emptyRequiredFields: FormItem[] = [];
    const invalidPatternFields: FormItem[] = [];
    const invalidLengthFields: FormItem[] = [];
    const invalidRangeFields: FormItem[] = [];
    const invalidArrayFields: FormItem[] = [];

    items.forEach((item) => {
      const value = formValues[item.key];
      let isEmpty = false;

      if (item.required) {
        if (item.isArray) {
          // 数组类型的必填项检查
          if (!Array.isArray(value) || value.length === 0) {
            isEmpty = true;
          } else {
            // 检查数组中的每个元素是否为空
            isEmpty = value.some((item: any) => !item || item === '');
          }
        } else {
          switch (item.type) {
            case 'switch':
              // Switch 组件，false 值也是有效值，只有 undefined/null 才是空
              isEmpty = value === undefined || value === null;
              break;
            case 'time':
              // DatePicker 组件，空字符串或 null 都是空值
              isEmpty = !value || value === '';
              break;
            default:
              // 其他组件，空字符串或 falsy 值都是空
              isEmpty = !value || value === '';
              break;
          }
        }
        
        if (isEmpty) {
          emptyRequiredFields.push(item);
        }
      }

      // 校验正则表达式
      if (item.pattern && value && !isEmpty) {
        try {
          const regex = new RegExp(item.pattern);
          if (Array.isArray(value)) {
            // 数组类型，检查每个元素
            const hasInvalidItem = value.some((item: any) => !regex.test(String(item)));
            if (hasInvalidItem) {
              invalidPatternFields.push(item);
            }
          } else {
            // 非数组类型
            if (!regex.test(String(value))) {
              invalidPatternFields.push(item);
            }
          }
        } catch (error) {
          console.error(`Invalid regex pattern for field ${item.key}:`, item.pattern, error);
        }
      }

      // 校验长度和范围
      if (value && !isEmpty) {
        if (item.isArray) {
          // 数组类型的校验
          const arrayValue = Array.isArray(value) ? value : [value];
          
          // 校验数组项数
          if (item.minItems !== undefined && arrayValue.length < item.minItems) {
            invalidArrayFields.push(item);
          }
          if (item.maxItems !== undefined && arrayValue.length > item.maxItems) {
            invalidArrayFields.push(item);
          }

          // 校验数组子项
          arrayValue.forEach((subValue: any, index: number) => {
            if (item.type === 'input') {
              // input 数组子项的 minLength/maxLength 校验
              const strValue = String(subValue);
              if (item.minLength !== undefined && strValue.length < item.minLength) {
                invalidLengthFields.push(item);
              }
              if (item.maxLength !== undefined && strValue.length > item.maxLength) {
                invalidLengthFields.push(item);
              }
            } else if (item.type === 'numberInput') {
              // numberInput 数组子项的 min/max 校验
              const numValue = Number(subValue);
              if (item.min !== undefined && numValue < item.min) {
                invalidRangeFields.push(item);
              }
              if (item.max !== undefined && numValue > item.max) {
                invalidRangeFields.push(item);
              }
            }
          });
        } else {
          // 非数组类型的校验
          if (item.type === 'input') {
            // input 类型的 minLength/maxLength 校验
            const strValue = String(value);
            if (item.minLength !== undefined && strValue.length < item.minLength) {
              invalidLengthFields.push(item);
            }
            if (item.maxLength !== undefined && strValue.length > item.maxLength) {
              invalidLengthFields.push(item);
            }
          } else if (item.type === 'numberInput' || item.type === 'time') {
            // numberInput 和 time 类型的 min/max 校验
            const numValue = Number(value);
            if (item.min !== undefined && numValue < item.min) {
              invalidRangeFields.push(item);
            }
            if (item.max !== undefined && numValue > item.max) {
              invalidRangeFields.push(item);
            }
          }
        }
      }
    });

    // 处理空值错误
    if (emptyRequiredFields.length > 0) {
      const fieldNames = emptyRequiredFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`请填写必填项${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个未填写的字段
      const firstEmptyField = document.querySelector(
        `[data-key="${emptyRequiredFields[0].key}"]`,
      ) as HTMLElement;
      if (firstEmptyField) {
        const input = firstEmptyField.querySelector('input, .ant-select-selector, .ant-picker-input') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }

    // 处理正则校验错误
    if (invalidPatternFields.length > 0) {
      const fieldNames = invalidPatternFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`格式不正确${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个格式错误的字段
      const firstInvalidField = document.querySelector(
        `[data-key="${invalidPatternFields[0].key}"]`,
      ) as HTMLElement;
      if (firstInvalidField) {
        const input = firstInvalidField.querySelector('input, .ant-select-selector, .ant-picker-input') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }

    // 处理长度校验错误
    if (invalidLengthFields.length > 0) {
      const fieldNames = invalidLengthFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`长度不符合要求${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个长度错误的字段
      const firstInvalidField = document.querySelector(
        `[data-key="${invalidLengthFields[0].key}"]`,
      ) as HTMLElement;
      if (firstInvalidField) {
        const input = firstInvalidField.querySelector('input, .ant-select-selector, .ant-picker-input') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }

    // 处理范围校验错误
    if (invalidRangeFields.length > 0) {
      const fieldNames = invalidRangeFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`数值超出范围${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个范围错误的字段
      const firstInvalidField = document.querySelector(
        `[data-key="${invalidRangeFields[0].key}"]`,
      ) as HTMLElement;
      if (firstInvalidField) {
        const input = firstInvalidField.querySelector('input, .ant-select-selector, .ant-picker-input') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }

    // 处理数组校验错误
    if (invalidArrayFields.length > 0) {
      const fieldNames = invalidArrayFields
        .filter((field) => field.label)
        .map((field) => field.label)
        .join('、');
      message.warning(`数组项数不符合要求${fieldNames ? ': ' + fieldNames : ''}`);

      // 聚焦到第一个数组错误的字段
      const firstInvalidField = document.querySelector(
        `[data-key="${invalidArrayFields[0].key}"]`,
      ) as HTMLElement;
      if (firstInvalidField) {
        const input = firstInvalidField.querySelector('input, .ant-select-selector, .ant-picker-input') as HTMLElement;
        if (input) {
          input.focus();
        }
      }
      return false;
    }

    return true;
  };

  const renderFormItem = (formItem: FormItem) => {
    // const isDisabled = Boolean(!isLastOne || itemText);
    const isDisabled = Boolean(!isLastOne);

    // 处理数组类型的表单项
    if (formItem.isArray) {
      const currentValues = formValues[formItem.key] || [];
      
      const addItem = () => {
        // 检查是否超过最大项数限制
        if (formItem.maxItems !== undefined && currentValues.length >= formItem.maxItems) {
          message.warning(`${formItem.label} 最多只能添加 ${formItem.maxItems} 项`);
          return;
        }
        const newValues = [...currentValues, ''];
        setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
      };

      const removeItem = (index: number) => {
        // 检查是否低于最小项数限制
        if (formItem.minItems !== undefined && currentValues.length <= formItem.minItems) {
          message.warning(`${formItem.label} 至少需要保留 ${formItem.minItems} 项`);
          return;
        }
        const newValues = currentValues.filter((_: any, i: number) => i !== index);
        setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
      };

      const updateItem = (index: number, value: any) => {
        const newValues = [...currentValues];
        newValues[index] = value;
        setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
      };

      switch (formItem.type) {
        case 'input':
          return (
            <div key={formItem.key} className="mb-4">
              <div className="mb-2 flex">
                <div className="text-left text-sm font-font-weight-600 text-text-5">
                  {formItem.label}
                </div>
                {formItem.required && <div className="ml-1 text-error">*</div>}
                {formItem.description && (
                  <QuestionTip className="ml-1" title={formItem.description} />
                )}
              </div>
              <div data-key={formItem.key}>
                {currentValues?.map((value: string, index: number) => (
                  <div key={index} className="mb-2 flex items-center gap-2">
                    <Input
                      style={{ flex: 1 }}
                      disabled={isDisabled}
                      placeholder={formItem.description || `请输入${formItem.label}`}
                      value={value}
                      onChange={(e) => updateItem(index, e.target.value)}
                      maxLength={formItem.maxLength}
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<MinusOutlined />}
                      onClick={() => removeItem(index)}
                      disabled={isDisabled}
                      className="text-gray-400 hover:text-red-500"
                    />
                  </div>
                ))}
                {(!formItem.maxItems || currentValues.length < formItem.maxItems) && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusOutlined />}
                    onClick={addItem}
                    disabled={isDisabled}
                    className="flex items-center !justify-start"
                  >
                    添加
                  </Button>
                )}
              </div>
            </div>
          );
        case 'numberInput':
          return (
            <div key={formItem.key} className="mb-4">
              <div className="mb-2 flex">
                <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
                {formItem.required && <div className="ml-1 text-error">*</div>}
                {formItem.description && (
                  <QuestionTip className="ml-1" title={formItem.description} />
                )}
              </div>
              <div data-key={formItem.key}>
                {currentValues?.map((value: number, index: number) => (
                  <div key={index} className="mb-2 flex items-center gap-2">
                    <InputNumber
                      style={{ flex: 1 }}
                      disabled={isDisabled}
                      placeholder={formItem.description || `请输入${formItem.label}`}
                      value={value}
                      onChange={(val) => updateItem(index, val)}
                      min={formItem.min}
                      max={formItem.max}
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<MinusOutlined />}
                      onClick={() => removeItem(index)}
                      disabled={isDisabled}
                      className="text-gray-400 hover:text-red-500"
                    />
                  </div>
                ))}
                {(!formItem.maxItems || currentValues.length < formItem.maxItems) && (
                  <Button
                    type="text"
                    icon={<PlusOutlined />}
                    onClick={addItem}
                    disabled={isDisabled}
                    className="flex items-center !justify-start"
                  >
                    添加
                  </Button>
                )}
              </div>
            </div>
          );
        case 'select':
          return (
            <div key={formItem.key} className="mb-4">
              <div className="mb-2 flex">
                <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
                {formItem.required && <div className="ml-1 text-error">*</div>}
                {formItem.description && (
                  <QuestionTip className="ml-1" title={formItem.description} />
                )}
              </div>
              <div data-key={formItem.key}>
                <Select
                  style={{ width: '100%' }}
                  disabled={isDisabled}
                  placeholder={formItem.description || `请选择${formItem.label}`}
                  value={currentValues}
                  options={formItem.list}
                  mode="multiple"
                  onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                />
              </div>
            </div>
          );
        default:
          return null;
      }
    }

    // 处理非数组类型的表单项
    switch (formItem.type) {
      case 'input':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-font-weight-600 text-text-5">
                {formItem.label}
              </div>
              {formItem.required && <div className="ml-1 text-error">*</div>}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Input
                style={{ width: '100%' }}
                disabled={isDisabled}
                placeholder={formItem.description || `请输入${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? ''}
                onChange={(e) =>
                  setFormValues((prev) => ({ ...prev, [formItem.key]: e.target.value }))
                }
                maxLength={formItem.maxLength}
              />
            </div>
          </div>
        );
      case 'numberInput':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="ml-1 text-error">*</div>}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <InputNumber
                style={{ width: '100%' }}
                disabled={isDisabled}
                placeholder={formItem.description || `请输入${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? undefined}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                min={formItem.min}
                max={formItem.max}
              />
            </div>
          </div>
        );
      case 'select':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="ml-1 text-error">*</div>}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Select
                style={{ width: '100%' }}
                disabled={isDisabled}
                placeholder={formItem.description || `请选择${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? undefined}
                options={formItem.list}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
              />
            </div>
          </div>
        );
      case 'cascader':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="ml-1 text-error">*</div>}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <Cascader
                style={{ width: '100%' }}
                disabled={isDisabled}
                options={formItem.list}
                placeholder={formItem.description || `请选择${formItem.label}`}
                value={formValues[formItem.key] ?? formItem.value ?? []}
                onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
              />
            </div>
          </div>
        );
      case 'switch':
        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex items-center justify-between">
              <div className="flex items-center">
                <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
                {formItem.required && <div className="ml-1 text-error">*</div>}
                {formItem.description && (
                  <QuestionTip className="ml-1" title={formItem.description} />
                )}
              </div>
              <div data-key={formItem.key}>
                <Switch
                  disabled={isDisabled}
                  checked={formValues[formItem.key] ?? formItem.value ?? false}
                  onChange={(checked) => setFormValues((prev) => ({ ...prev, [formItem.key]: checked }))}
                />
              </div>
            </div>
          </div>
        );
      case 'time':
        // 根据 valueType 确定日期格式
        const getDateFormat = (valueType: string) => {
          switch (valueType) {
            case 'date':
              return 'YYYY-MM-DD';
            case 'time':
              return 'HH:mm:ss';
            case 'datetime':
              return 'YYYY-MM-DD HH:mm:ss';
            default:
              return 'YYYY-MM-DD HH:mm:ss';
          }
        };

        const getDatePickerType = (valueType: string) => {
          switch (valueType) {
            case 'date':
              return 'date';
            case 'time':
              return 'time';
            case 'datetime':
              return 'datetime';
            default:
              return 'datetime';
          }
        };

        const dateFormat = getDateFormat(formItem.valueType);
        const pickerType = getDatePickerType(formItem.valueType);
        
        // 处理日期值
        const getDateValue = (value: any) => {
          if (!value) return null;
          if (dayjs.isDayjs(value)) return value;
          return dayjs(value, dateFormat);
        };

        return (
          <div key={formItem.key} className="mb-4">
            <div className="mb-2 flex">
              <div className="text-left text-sm font-semibold text-[#1D2129]">{formItem.label}</div>
              {formItem.required && <div className="ml-1 text-error">*</div>}
              {formItem.description && (
                <QuestionTip className="ml-1" title={formItem.description} />
              )}
            </div>
            <div data-key={formItem.key}>
              <DatePicker
                style={{ width: '100%' }}
                disabled={isDisabled}
                placeholder={formItem.description || `请选择${formItem.label}`}
                value={getDateValue(formValues[formItem.key] ?? formItem.value)}
                format={dateFormat}
                picker={pickerType as any}
                onChange={(date, dateString) => {
                  setFormValues((prev) => ({ ...prev, [formItem.key]: dateString }));
                }}
                disabledDate={(current) => {
                  if (formItem.min !== undefined) {
                    const minDate = dayjs().add(formItem.min, 'day');
                    if (current && current.isBefore(minDate, 'day')) {
                      return true;
                    }
                  }
                  if (formItem.max !== undefined) {
                    const maxDate = dayjs().add(formItem.max, 'day');
                    if (current && current.isAfter(maxDate, 'day')) {
                      return true;
                    }
                  }
                  return false;
                }}
              />
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  // 如果参数超过3个，使用表格形式展示
  if (formItems.length > 0) {
    // 计算每行可以放置多少对参数（参数名+参数值）
    const pairsPerRow = Math.floor(columns / 2);
    // 计算需要多少行
    const totalRows = Math.ceil(formItems.length / pairsPerRow);
    return (
      <div className="rounded-xl bg-[transparent] p-4">
        <div className="mb-4 text-sm font-font-weight-400 text-text-3">
          <pre>{description || '请填写以下参数'}</pre>
        </div>
        
        {/* 多列表格形式展示 */}
        <div className="!outline !outline-[1px] !outline-[#D8DCE3] rounded-lg overflow-hidden">
          <div className="flex flex-wrap">
            {formItems.map((formItem, index) => {
              // const isDisabled = Boolean(!isLastOne || itemText);
              const isDisabled = Boolean(!isLastOne);
              
              // 计算当前参数在第几行
              const currentRow = Math.floor(index / pairsPerRow);
              // 计算当前参数在当前行的位置
              const positionInRow = index % pairsPerRow;
              // 判断是否是当前行的最后一个参数
              const isLastInRow = positionInRow === pairsPerRow - 1;
              // 判断是否是最后一个参数
              const isLastItem = index === formItems.length - 1;
              
              const renderField = () => {
                                // 处理数组类型的表单项
                if (formItem.isArray) {
                  const currentValues = formValues[formItem.key] || [];
                  
                  const addItem = () => {
                    // 检查是否超过最大项数限制
                    if (formItem.maxItems !== undefined && currentValues.length >= formItem.maxItems) {
                      message.warning(`${formItem.label} 最多只能添加 ${formItem.maxItems} 项`);
                      return;
                    }
                    const newValues = [...currentValues, ''];
                    setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
                  };

                  const removeItem = (index: number) => {
                    // 检查是否低于最小项数限制
                    if (formItem.minItems !== undefined && currentValues.length <= formItem.minItems) {
                      message.warning(`${formItem.label} 至少需要保留 ${formItem.minItems} 项`);
                      return;
                    }
                    const newValues = currentValues.filter((_: any, i: number) => i !== index);
                    setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
                  };

                  const updateItem = (index: number, value: any) => {
                    const newValues = [...currentValues];
                    newValues[index] = value;
                    setFormValues((prev) => ({ ...prev, [formItem.key]: newValues }));
                  };

                  switch (formItem.type) {
                    case 'input':
                      return (
                        <div className="w-full">
                          {currentValues?.map((value: string, index: number) => (
                            <div key={index} className="mb-2 flex items-center gap-2 w-full">
                              <Input
                                style={{ flex: 1 }}
                                disabled={isDisabled}
                                placeholder={formItem.description || `请输入${formItem.label}`}
                                value={value}
                                onChange={(e) => updateItem(index, e.target.value)}
                                maxLength={formItem.maxLength}
                              />
                              <Button
                                type="text"
                                size="small"
                                icon={<MinusOutlined />}
                                onClick={() => removeItem(index)}
                                disabled={isDisabled}
                                className="text-gray-400 hover:text-red-500"
                              />
                            </div>
                          ))}
                          {(!formItem.maxItems || currentValues.length < formItem.maxItems) && (
                            <Button
                              type="text"
                              icon={<PlusOutlined />}
                              onClick={addItem}
                              disabled={isDisabled}
                              className="flex items-center !justify-start"
                            >
                              添加
                            </Button>
                          )}
                        </div>
                      );
                    case 'numberInput':
                      return (
                        <div className="w-full">
                          {currentValues?.map((value: number, index: number) => (
                            <div key={index} className="mb-2 flex items-center gap-2">
                              <InputNumber
                                style={{ flex: 1 }}
                                disabled={isDisabled}
                                placeholder={formItem.description || `请输入${formItem.label}`}
                                value={value}
                                onChange={(val) => updateItem(index, val)}
                                min={formItem.min}
                                max={formItem.max}
                              />
                              <Button
                                type="text"
                                size="small"
                                icon={<MinusOutlined />}
                                onClick={() => removeItem(index)}
                                disabled={isDisabled}
                                className="text-gray-400 hover:text-red-500"
                              />
                            </div>
                          ))}
                          {(!formItem.maxItems || currentValues.length < formItem.maxItems) && (
                            <Button
                              type="dashed"
                              icon={<PlusOutlined />}
                              onClick={addItem}
                              disabled={isDisabled}
                              className="flex items-center !justify-start"
                            >
                              添加
                            </Button>
                          )}
                        </div>
                      );
                    case 'select':
                      return (
                        <Select
                          style={{ width: '100%' }}
                          disabled={isDisabled}
                          placeholder={formItem.description || `请选择${formItem.label}`}
                          value={currentValues}
                          options={formItem.list}
                          mode="multiple"
                          onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                        />
                      );
                    default:
                      return null;
                  }
                }

                // 处理非数组类型的表单项
                switch (formItem.type) {
                  case 'input':
                    return (
                      <Input
                        style={{ width: '100%' }}
                        disabled={isDisabled}
                        placeholder={formItem.description || `请输入${formItem.label}`}
                        value={formValues[formItem.key] ?? formItem.value ?? ''}
                        onChange={(e) =>
                          setFormValues((prev) => ({ ...prev, [formItem.key]: e.target.value }))
                        }
                        maxLength={formItem.maxLength}
                      />
                    );
                  case 'numberInput':
                    return (
                      <InputNumber
                        style={{ width: '100%' }}
                        disabled={isDisabled}
                        placeholder={formItem.description || `请输入${formItem.label}`}
                        value={formValues[formItem.key] ?? formItem.value ?? undefined}
                        onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                        min={formItem.min}
                        max={formItem.max}
                      />
                    );
                  case 'select':
                    return (
                      <Select
                        style={{ width: '100%' }}
                        disabled={isDisabled}
                        placeholder={formItem.description || `请选择${formItem.label}`}
                        value={formValues[formItem.key] ?? formItem.value ?? undefined}
                        options={formItem.list}
                        onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                      />
                    );
                  case 'cascader':
                    return (
                      <Cascader
                        style={{ width: '100%' }}
                        disabled={isDisabled}
                        options={formItem.list}
                        placeholder={formItem.description || `请选择${formItem.label}`}
                        value={formValues[formItem.key] ?? formItem.value ?? []}
                        onChange={(value) => setFormValues((prev) => ({ ...prev, [formItem.key]: value }))}
                      />
                    );
                  case 'switch':
                    return (
                      <div className="flex justify-center">
                        <Switch
                          disabled={isDisabled}
                          checked={formValues[formItem.key] ?? formItem.value ?? false}
                          onChange={(checked) => setFormValues((prev) => ({ ...prev, [formItem.key]: checked }))}
                        />
                      </div>
                    );
                  case 'time':
                    // 根据 valueType 确定日期格式
                    const getDateFormat = (valueType: string) => {
                      switch (valueType) {
                        case 'date':
                          return 'YYYY-MM-DD';
                        case 'time':
                          return 'HH:mm:ss';
                        case 'datetime':
                          return 'YYYY-MM-DD HH:mm:ss';
                        default:
                          return 'YYYY-MM-DD HH:mm:ss';
                      }
                    };

                    const getDatePickerType = (valueType: string) => {
                      switch (valueType) {
                        case 'date':
                          return 'date';
                        case 'time':
                          return 'time';
                        case 'datetime':
                          return 'datetime';
                        default:
                          return 'datetime';
                      }
                    };

                    const dateFormat = getDateFormat(formItem.valueType);
                    const pickerType = getDatePickerType(formItem.valueType);
                    
                    // 处理日期值
                    const getDateValue = (value: any) => {
                      if (!value) return null;
                      if (dayjs.isDayjs(value)) return value;
                      return dayjs(value, dateFormat);
                    };

                    return (
                      <DatePicker
                        style={{ width: '100%' }}
                        disabled={isDisabled}
                        placeholder={formItem.description || `请选择${formItem.label}`}
                        value={getDateValue(formValues[formItem.key] ?? formItem.value)}
                        format={dateFormat}
                        picker={pickerType as any}
                        onChange={(date, dateString) => {
                          setFormValues((prev) => ({ ...prev, [formItem.key]: dateString }));
                        }}
                        disabledDate={(current) => {
                          if (formItem.min !== undefined) {
                            const minDate = dayjs().add(formItem.min, 'day');
                            if (current && current.isBefore(minDate, 'day')) {
                              return true;
                            }
                          }
                          if (formItem.max !== undefined) {
                            const maxDate = dayjs().add(formItem.max, 'day');
                            if (current && current.isAfter(maxDate, 'day')) {
                              return true;
                            }
                          }
                          return false;
                        }}
                      />
                    );
                  default:
                    return null;
                }
              };

              return (
                <div 
                  key={formItem.key} 
                  className="flex" 
                  style={{ 
                    width: isLastItem && !isLastInRow ? '100%' : `${100 / pairsPerRow}%`
                    // width: `${100 / pairsPerRow}%`
                  }}
                >
                  {/* 参数名 */}
                  <div 
                    className="flex items-center !outline !outline-[1px] !outline-[#D8DCE3] p-3 bg-gray-100 justify-center"
                    style={{ 
                      width: labelWidth,
                      flexShrink: 0 // 防止参数名被压缩
                    }}
                  >
                    <span className="text-sm font-medium text-text-5">{formItem.label}</span>
                    {formItem.required && <span className="ml-1 text-error">*</span>}
                    {formItem.description && (
                      <QuestionTip className="ml-1" title={formItem.description} />
                    )}
                  </div>
                  {/* 参数值 */}
                  <div 
                    data-key={formItem.key} 
                    className="!outline !outline-[0.5px] !outline-[#D8DCE3] p-3 flex items-center justify-start w-full"
                    style={{ 
                      flex: 1 // 参数值占满剩余空间
                    }}
                  >
                    {renderField()}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        
        <div className="mt-4 flex justify-end">
          <Button
            type="primary"
            onClick={() => {
              if (checkRequiredFields(formItems)) {
                onSend(JSON.stringify(formValues));
              }
            }}
            disabled={!isLastOne || itemText}
          >
            提交
          </Button>
        </div>
      </div>
    );
  }

  // 参数不超过3个时，使用原来的垂直布局
  return (
    <div className="rounded-xl bg-[transparent] p-4 !outline !outline-[1px] !outline-[#D8DCE3] rounded-lg p-3">
      <div className="mb-2 text-sm font-font-weight-400 text-text-3">
        <pre>{description || '请填写以下参数'}</pre>
      </div>
      {formItems.map((formItem) => renderFormItem(formItem))}
      <div className="mt-2 flex items-center justify-end">
        <Button
          type="primary"
          onClick={() => {
            if (checkRequiredFields(formItems)) {
              onSend(JSON.stringify(formValues));
            }
          }}
          className="ml-2"
          disabled={!isLastOne || itemText}
        >
          提交
        </Button>
      </div>
    </div>
  );
};

export default FormRenderer; 